{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Building a Fraud Prediction Model with EvalML\n",
    "\n",
    "In this demo, we will build an optimized fraud prediction model using EvalML. To optimize the pipeline, we will set up an objective function to minimize the percentage of total transaction value lost to fraud. At the end of this demo, we also show you how introducing the right objective during the training results in a much better than using a generic machine learning metric like AUC."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import evalml\n",
    "from evalml import AutoMLSearch\n",
    "from evalml.objectives import FraudCost"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Configure \"Cost of Fraud\" \n",
    "\n",
    "To optimize the pipelines toward the specific business needs of this model, we can set our own assumptions for the cost of fraud. These parameters are\n",
    "\n",
    "* `retry_percentage` - what percentage of customers will retry a transaction if it is declined?\n",
    "* `interchange_fee` - how much of each successful transaction do you collect?\n",
    "* `fraud_payout_percentage` - the percentage of fraud will you be unable to collect\n",
    "* `amount_col` - the column in the data the represents the transaction amount\n",
    "\n",
    "Using these parameters, EvalML determines attempt to build a pipeline that will minimize the financial loss due to fraud."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fraud_objective = FraudCost(\n",
    "    retry_percentage=0.5,\n",
    "    interchange_fee=0.02,\n",
    "    fraud_payout_percentage=0.75,\n",
    "    amount_col=\"amount\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Search for best pipeline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In order to validate the results of the pipeline creation and optimization process, we will save some of our data as the holdout set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "X, y = evalml.demos.load_fraud(n_rows=5000)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "EvalML natively supports one-hot encoding. Here we keep 1 out of the 6 categorical columns to decrease computation time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "cols_to_drop = [\"datetime\", \"expiration_date\", \"country\", \"region\", \"provider\"]\n",
    "for col in cols_to_drop:\n",
    "    X.ww.pop(col)\n",
    "\n",
    "X_train, X_holdout, y_train, y_holdout = evalml.preprocessing.split_data(\n",
    "    X, y, problem_type=\"binary\", test_size=0.2, random_seed=0\n",
    ")\n",
    "\n",
    "X.ww"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because the fraud labels are binary, we will use `AutoMLSearch(X_train=X_train, y_train=y_train, problem_type='binary')`. When we call `.search()`, the search for the best pipeline will begin. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl = AutoMLSearch(\n",
    "    X_train=X_train,\n",
    "    y_train=y_train,\n",
    "    problem_type=\"binary\",\n",
    "    objective=fraud_objective,\n",
    "    additional_objectives=[\"auc\", \"f1\", \"precision\"],\n",
    "    allowed_model_families=[\"random_forest\", \"linear_model\"],\n",
    "    max_batches=1,\n",
    "    optimize_thresholds=True,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "automl.search(interactive_plot=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### View rankings and select pipelines\n",
    "\n",
    "Once the fitting process is done, we can see all of the pipelines that were searched, ranked by their score on the fraud detection objective we defined."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl.rankings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To select the best pipeline we can call `automl.best_pipeline`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_pipeline = automl.best_pipeline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Describe pipelines\n",
    "\n",
    "We can get more details about any pipeline created during the search process, including how it performed on other objective functions, by calling the `describe_pipeline` method and passing the `id` of the pipeline of interest."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl.describe_pipeline(automl.rankings.iloc[1][\"id\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate on holdout data\n",
    "\n",
    "Finally, since the best pipeline is already trained, we evaluate it on the holdout data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we can score the pipeline on the holdout data using both our fraud cost objective and the AUC (Area under the ROC Curve) objective."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_pipeline.score(X_holdout, y_holdout, objectives=[\"auc\", fraud_objective])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Why optimize for a problem-specific objective?\n",
    "\n",
    "To demonstrate the importance of optimizing for the right objective, let's search for another pipeline using AUC, a common machine learning metric. After that, we will score the holdout data using the fraud cost objective to see how the best pipelines compare."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl_auc = AutoMLSearch(\n",
    "    X_train=X_train,\n",
    "    y_train=y_train,\n",
    "    problem_type=\"binary\",\n",
    "    objective=\"auc\",\n",
    "    additional_objectives=[\"f1\", \"precision\"],\n",
    "    max_batches=1,\n",
    "    allowed_model_families=[\"random_forest\", \"linear_model\"],\n",
    "    optimize_thresholds=True,\n",
    "    verbose=True,\n",
    ")\n",
    "\n",
    "automl_auc.search(interactive_plot=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Like before, we can look at the rankings of all of the pipelines searched and pick the best pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "automl_auc.rankings"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "best_pipeline_auc = automl_auc.best_pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# get the fraud score on holdout data\n",
    "best_pipeline_auc.score(X_holdout, y_holdout, objectives=[\"auc\", fraud_objective])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fraud score on fraud optimized again\n",
    "best_pipeline.score(X_holdout, y_holdout, objectives=[\"auc\", fraud_objective])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When we optimize for AUC, we can see that the AUC score from this pipeline performs better compared to the AUC score from the pipeline optimized for fraud cost; however, the losses due to fraud are a much larger percentage of the total transaction amount when optimized for AUC and much smaller when optimized for fraud cost. As a result, we lose a noticable percentage of the total transaction amount by not optimizing for fraud cost specifically.\n",
    "\n",
    "Optimizing for AUC does not take into account the user-specified `retry_percentage`, `interchange_fee`, `fraud_payout_percentage` values, which could explain the decrease in fraud performance. Thus, the best pipelines may produce the highest AUC but may not actually reduce the amount loss due to your specific type fraud.\n",
    "\n",
    "This example highlights how performance in the real world can diverge greatly from machine learning metrics."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
